<?php
$xh=$_COOKIE["xh"]; //获取各 Cookie 信息
$pwd=$_COOKIE["pwd"];
$rememberMe=$_COOKIE["rememberMe"];
if($_POST) {//提交有数据
 session_start();
 if ($_POST['rememberMe'] === 'on') { //需要记住用户信息，则设置 Cookie
 setcookie("xh", $_POST['xh'], time() + 7 * 24 * 3600);
 setcookie("pwd", $_POST['pwd'], time() + 7 * 24 * 3600);
 setcookie("rememberMe", $_POST['rememberMe'], time() + 7 * 24 * 3600);
 } else { //无需记住用户信息，则删除 Cookie
 setcookie("xh");
 setcookie("pwd");
 setcookie("rememberMe");
 }
 try {
 $db = new PDO('mysql:host=localhost;dbname=db2', 'root', '12qwas');
 $ps = $db->prepare("select * from students where xh=? and pwd=?");
 $ps->execute(array($_POST["xh"],$_POST["pwd"]));
 if($r=$ps->fetch(PDO::FETCH_ASSOC)){//若成功登录
 var_dump($r); // array(4) { ["xh"]=> string(9) "213110101" ["name"]=> string(6) "张三" ["tel"]=> string(5) '111' ['pwd']=> string(6) '123456' }
 $_SESSION['user']=$r; //将登录的用户信息保存到 Session 中
 header("Location: index.php") or die(); //重定向到 index.php 来显示通讯录
 }
 unset($_SESSION['user']); //登录失败，则删除 Session 中保存的信息
 throw new Exception('用户名或口令错误，登录失败~');
 } catch (Exception $e) {
 $msg = $e->getMessage();//插入数据库错误，则获取错误信息用于提醒用户
 }
} ?>
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>用户登录</title>
 <style>
 h1{ color:red; }
 input{ padding:10px; margin: 5px 0; border-radius: 8px; }
 .msg{ color:red; margin:10px 0; }
 label{ margin:10px 0; display: block;}
 </style>
</head>
<body>
<h1>用户登录</h1>
<form method="post" >
 学号：<input name="xh" value="<?= $_POST['xh']??$xh ?>" /><br>
 密码：<input type="password" name="pwd" value="<?= $_POST['pwd']??$pwd ?>" /><br>
 <label>
 <input type="checkbox" name="rememberMe"<?= $_POST?($_POST['rememberMe']?' checked':''):($rememberMe?" checked":"") ?> />
 记住我的信息一周
 </label>
 <div class="msg"><?= $msg ?></div>
 <input type="submit" value=" 提交数据 ">
    <input type="button" value=" 注册新用户 " onclick="location.href='modify.php'">
</form>
</body>
</html>